import _ from 'lodash';
import Config, { authData } from '../config';
import * as UserService from './userService';

const apiDomain = Config.apiDomain;
const timeout = 10000;

function filterJSON(res) {
    console.log("res9:" + JSON.stringify(res));
    try {
        console.log("length:" + res.headers.get("content-length"));
        return res.json();

    }
    catch (e) {
        throw new Error('data format error');
    }
}

function filterStatus(res) {
    console.log("res:" + res)
    if (res.ok) {
        return res;
    } else {
        console.log("error");
        return ""
    }
}

function timeoutFetch(ms, promise) {
    return new Promise((resolve, reject) => {
        console.log("timeout:" + ms);
        const timer = setTimeout(() => {
            reject(new Error("fetch time out"));
        }, ms);


        promise.then((response) => {
            
            console.log("res41:" + JSON.stringify(response));
            resolve(response);
            clearTimeout(timer);
        }, (err) => {
            clearTimeout(timer);
            reject(err);
        });

    })
}

export function request(uri, type = "GET", headers = {}, data = "") {


    if (!_.startsWith(uri, "http")) {
        uri = Config.apiDomain + uri;
    }

    let fetchOption = {
        method: type,
        headers: headers
    };

    if (type === "POST") {
        fetchOption.body = data
    }

    if (__DEV__) {
        console.log("fetch data from uri:");
        console.log(uri);
        console.log("type");
        console.log(type);
        console.log("headers:");
        console.log(headers);
        console.log("data:");
        console.log(data);
    }

    return timeoutFetch(timeout, fetch(uri, fetchOption))
        .then(filterStatus)
        .then(filterJSON)
        .catch(function (error) {
            console.log(error);
            alert("请求超时，请重试");
        });

}

export function get(uri, headers = {}) {
    return request(uri, "GET", headers);
}

export function post(uri, data = "", headers = {}) {
    if (!headers["Content-type"]) {
        headers["Content-type"] = 'application/json';
    }
    return request(uri, "POST", headers, data);
}

export function remove(uri, headers = {}) {
    return request(uri, "DELETE", headers);
}